package org.algorithm.kmp;

import java.util.Arrays;

public class KMP {

    public static void main(String[] args) {
        String subStr = "ababacd";
        System.out.println(Arrays.toString(kmpNext(subStr)));

        int index = kmpSearch("ioipoipi   asdfsdfababacdlkjlalsf", subStr);
        System.out.println(index);
    }

    public static int kmpSearch(String str, String subStr) {

        int[] next = kmpNext(subStr);
        for (int i = 0, j = 0; i < str.length(); i++) {

            while (j > 0 && str.charAt(i) != subStr.charAt(j)) {
                j = next[j - 1];
            }
            if (str.charAt(i) == subStr.charAt(j)) {
                j++;
            }
            if (j == next.length - 1) {
                return i - j;
            }
        }
        return -1;
    }


    public static int[] kmpNext(String subStr) {
        // TODO: 2022/3/21 代表已匹配前后锥字串的长度
        int[] next = new int[subStr.length()];
        next[0] = 0;
        for (int i = 1, j = 0; i < subStr.length(); i++) {

            while (j > 0 && subStr.charAt(i) != subStr.charAt(j)) {
                j = next[j - 1];
            }

            if (subStr.charAt(i) == subStr.charAt(j)) {
                j++;
            }

            next[i] = j;
        }
        return next;
    }
}
